﻿/*
 DotNetNuke - http://www.dotnetnuke.com
 Copyright (c) 2002-2010 by DotNetNuke Corp.

 Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
 documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
 the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
 to permit persons to whom the Software is furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in all copies or substantial portions 
 of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
 TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
 THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
 CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
 DEALINGS IN THE SOFTWARE.

*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.IO;

using System.Web;
using System.Xml;

using DotNetNuke.Common;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Entities.Portals;
using DotNetNuke.Modules.UserDefinedTable.Security;
using DotNetNuke.Modules.UserDefinedTable.Serialization;
using DotNetNuke.Services.Exceptions;
using DotNetNuke.Services.FileSystem;
using DotNetNuke.Services.Search;



namespace DotNetNuke.Modules.UserDefinedTable
{



  public class BusinessController : ISearchable, IPortable, IPortable2
  {



    public enum SettingsType
    {
      ModuleSettings,
      TabModuleSettings
    }



    public string ExportModule(int ModuleID)
    {
      return this.ExportModule(ModuleID, Null.NullInteger);
    }




    public string ExportModule(int ModuleID, int TabID)
    {
      return this.ExportModule(ModuleID, TabID, Null.NullInteger);
    }




    public string ExportModule(int ModuleID, int TabID, int MaxNumberOfItems)
    {
      DataSet set = this.ExportModuleDataSet(ModuleID, TabID);
      if (MaxNumberOfItems > Null.NullInteger)
      {
        int num2 = MaxNumberOfItems;
        for (int i = set.Tables[DataSetTableName.Data].Rows.Count - 1; i >= num2; i += -1)
        {
          set.Tables[DataSetTableName.Data].Rows.RemoveAt(i);
        }
      }
      return set.GetXml();
    }




    public DataSet ExportModuleDataSet(int ModuleID, int TabID)
    {
      DataSet dataSet = null;
      if (TabID == Null.NullInteger)
      {
        dataSet = new UserDefinedTableController(ModuleID).GetDataSet(false);
        dataSet.Tables.Add(GetSettingsTable(ModuleID, SettingsType.ModuleSettings));
        return dataSet;
      }
      ModuleInfo module = new ModuleController().GetModule(ModuleID, TabID);
      UserDefinedTableController controller2 = new UserDefinedTableController(module);
      dataSet = controller2.GetDataSet(false);
      dataSet.Tables.Add(GetSettingsTable(ModuleID, SettingsType.ModuleSettings));
      dataSet.Tables.Add(GetSettingsTable(module.TabModuleID, SettingsType.TabModuleSettings));
      dataSet.Tables.Add(this.GetStylesheetTable(controller2.Settings, module.PortalID));
      return dataSet;
    }




    public SearchItemInfoCollection GetSearchItems(ModuleInfo ModInfo)
    {
      SearchItemInfoCollection infos2 = new SearchItemInfoCollection();
      UserDefinedTableController controller = new UserDefinedTableController(ModInfo);

      try
      {
        ModuleController controller2 = new ModuleController();

        if (Utilities.CBoolN(controller2.GetModuleSettings(ModInfo.ModuleID)[SettingName.ExcludeFromSearch], false))
          return infos2;

        DataSet dataSet = controller.GetDataSet(false);
        string str2 = controller.ColumnNameByDataType(dataSet, DataTypeNames.UDT_DataType_ChangedBy);
        string str = controller.ColumnNameByDataType(dataSet, DataTypeNames.UDT_DataType_ChangedAt);
        string str4, str5;
        SearchItemInfo info;

        foreach(DataRow current in dataSet.Tables[DataSetTableName.Data].Rows)
        {
          DateTime today = DateTime.Today;
          int author = 0;

          if ( !string.IsNullOrEmpty(str) && current[str] != DBNull.Value )
            today = (DateTime)current[str];

          if (!string.IsNullOrEmpty(str2) && DBNull.Value != current[str2])
            author = ModuleSecurity.UserId((string)current[str2], ModInfo.PortalID);

          string description = string.Empty;

          foreach (DataRow row2 in dataSet.Tables[DataSetTableName.Fields].Rows)
          {
            str5 = (string)row2[FieldsTableColumn.Type];
            str4 = (string)row2[FieldsTableColumn.Title];
            if (Convert.ToBoolean(row2[FieldsTableColumn.Visible]) && (str5.StartsWith("Text") | (str5 == DataTypeNames.UDT_DataType_String)))
              description = description + string.Format("{0} &bull; ", (string)current[str4]);
          }
          
          if (description.EndsWith("<br/>"))
            description = description.Substring(0, description.Length - 5);

          info = new SearchItemInfo(ModInfo.ModuleTitle, description, author, today, ModInfo.ModuleID, (string)current[DataTableColumn.RowId], description);
          infos2.Add(info);
        }
      }
      catch (Exception e)
      {
        Exception exc = e;
        DotNetNuke.Services.Exceptions.Exceptions.LogException(exc);
      }

      return infos2;
    }




    private static DataTable GetSettingsTable(int ID, SettingsType Type)
    {
      ModuleController controller = new ModuleController();
      Hashtable moduleSettings = null;
      DataTable table = null;
      switch (Type)
      {
        case SettingsType.ModuleSettings:
          moduleSettings = controller.GetModuleSettings(ID);
          table = new DataTable(DataSetTableName.Settings);
          break;

        case SettingsType.TabModuleSettings:
          moduleSettings = controller.GetTabModuleSettings(ID);
          table = new DataTable(DataSetTableName.TabSettings);
          break;
      }

      SortedList<string, string> list = new SortedList<string, string>();

      foreach (DictionaryEntry current in moduleSettings)
        list.Add((string)current.Key, (string)current.Value);

      DataColumn column2 = new DataColumn(SettingsTableColumn.Setting, typeof(string));
      column2.ColumnMapping = MappingType.Attribute;
      DataColumn column = column2;
      table.Columns.Add(column);
      column = new DataColumn(SettingsTableColumn.Value, typeof(string));
      column.ColumnMapping = MappingType.Attribute;
      table.Columns.Add(column);

      DataRow row;

      foreach (string str in list.Keys)
      {
        row = table.NewRow();
        row[SettingsTableColumn.Setting] = str;
        row[SettingsTableColumn.Value] = list[str];
        table.Rows.Add(row);
      }
      return table;
    }




    private DataTable GetStylesheetTable(Hashtable Settings, int portalId)
    {
      string str;
      string str3;
      DataTable table = new DataTable(DataSetTableName.Stylesheets);
      table.Columns.Add(new DataColumn(StylesheetTableColumn.NameOfSetting, typeof(string)));
      table.Columns.Add(new DataColumn(StylesheetTableColumn.LocalFilePath, typeof(string)));
      table.Columns.Add(new DataColumn(StylesheetTableColumn.Stylesheet, typeof(string)));
      string str2 = string.Format("UDT_{0}", Utilities.CStrN(Settings[SettingName.RenderingMethod], ""));
      if (str2 == SettingName.XslUserDefinedStyleSheet)
        str = (string)Settings[str2];

      else
        str = string.Empty;

      if (str.Length > 0)
      {
        DataRow row = table.NewRow();
        row[StylesheetTableColumn.NameOfSetting] = SettingName.XslUserDefinedStyleSheet;
        row[StylesheetTableColumn.LocalFilePath] = str;
        row[StylesheetTableColumn.Stylesheet] = LoadScript(str, portalId);
        table.Rows.Add(row);
      }
      if (Utilities.CBoolN(Settings[SettingName.TrackingEnabled], false))
        str3 = Utilities.CStrN(Settings[SettingName.TrackingScript], "");

      else
        str3 = string.Empty;

      if ((str3.Length > 0) && (str3 != "[AUTO]"))
      {
        DataRow row2 = table.NewRow();
        row2[StylesheetTableColumn.NameOfSetting] = SettingName.TrackingScript;
        row2[StylesheetTableColumn.LocalFilePath] = str3;
        row2[StylesheetTableColumn.Stylesheet] = LoadScript(str3, portalId);
        table.Rows.Add(row2);
      }
      return table;
    }




    public void ImportModule(int ModuleID, string Content, string Version, int UserID)
    {
      this.ImportModule(ModuleID, Null.NullInteger, Content, Version, UserID, false);
    }





    public void ImportModule(int ModuleID, int TabID, string Content, string Version, int UserID, bool IsInstance)
    {
      int scriptTimeout = System.Web.HttpContext.Current.Server.ScriptTimeout;
      try
      {
        System.Web.HttpContext.Current.Server.ScriptTimeout = 0x7fffffff;
        UserDefinedTableController controller = new UserDefinedTableController(ModuleID);
        using (DataSet set = new DataSet())
        {
          XmlNode content = DotNetNuke.Common.Globals.GetContent(Content, string.Empty);
          set.ReadXml(new XmlNodeReader(content));
          ModuleController controller2 = new ModuleController();
          int nullInteger = Null.NullInteger;

          if (TabID != Null.NullInteger)
            nullInteger = controller2.GetModule(ModuleID, TabID).TabModuleID;

          if ((nullInteger != Null.NullInteger) && (set.Tables[DataSetTableName.TabSettings] != null))
            foreach (DataRow current in set.Tables[DataSetTableName.TabSettings].Rows)
              controller2.UpdateTabModuleSetting(nullInteger, (string)current[SettingsTableColumn.Setting], (string)current[SettingsTableColumn.Value]);
            
          if (!IsInstance)
          {
            if (set.Tables[DataSetTableName.Settings] != null)
              foreach (DataRow current in set.Tables[DataSetTableName.Settings].Rows)
                controller2.UpdateModuleSetting(ModuleID, (string)current[SettingsTableColumn.Setting], (string)current[SettingsTableColumn.Value]);
              
            controller.ResetModule();
            int count = set.Tables[DataSetTableName.Fields].Rows.Count;

            foreach (DataRow row in set.Tables[DataSetTableName.Fields].Rows)
            {

              row[FieldsTableColumn.Id] = controller.AddField(
                  (string)row[FieldsTableColumn.Title]
                  , int.Parse(Utilities.CStrN(row, FieldsTableColumn.Order, count.ToString()))
                  , Utilities.CStrN(row, FieldsTableColumn.HelpText, "")
                  , bool.Parse(Utilities.CStrN(row, FieldsTableColumn.Required, "false"))
                  , Utilities.CStrN(row, FieldsTableColumn.Type, "")
                  , Utilities.CStrN(row, FieldsTableColumn.Default, "")
                  , bool.Parse(Utilities.CStrN(row, FieldsTableColumn.Visible, "false"))
                  , bool.Parse(Utilities.CStrN(row, FieldsTableColumn.ShowOnEdit, "true"))
                  , bool.Parse(Utilities.CStrN(row, FieldsTableColumn.Searchable, "false"))
                  , bool.Parse(Utilities.CStrN(row, FieldsTableColumn.IsPrivate, "false"))
                  , Utilities.CStrN(row, FieldsTableColumn.InputSettings, "")
                  , Utilities.CStrN(row, FieldsTableColumn.OutputSettings, "")
                  , bool.Parse(Utilities.CStrN(row, FieldsTableColumn.NormalizeFlag, "false"))
                  , Utilities.CStrN(row, FieldsTableColumn.ValidationRule, "")
                  , Utilities.CStrN(row, FieldsTableColumn.ValidationMessage, "")
                  , Utilities.CStrN(row, FieldsTableColumn.EditStyle, "")
                );

              count--;
            }
            
            if (set.Tables[DataSetTableName.Data] != null)
            {
              int num5 = set.Tables[DataSetTableName.Data].Rows.Count - 1;

              for (int i = 0; i <= num5; i++)
                controller.UpdateRow(set, i, true);
              
            }
          }
          if (set.Tables.Contains(DataSetTableName.Stylesheets))
          {
            PortalSettings portalSettings = DotNetNuke.Common.Globals.GetPortalSettings();

            string settingName;
            string str;
            string fileContent;
            string fileName;
            FolderInfo folder;

            foreach (DataRow row4 in set.Tables[DataSetTableName.Stylesheets].Rows)
            {
              settingName = (string)row4[StylesheetTableColumn.NameOfSetting];
              str = (string)row4[StylesheetTableColumn.LocalFilePath];
              fileContent = (string)row4[StylesheetTableColumn.Stylesheet];
              if (!File.Exists((portalSettings.HomeDirectoryMapPath + str).Replace("/", @"\")))
              {
                fileName = str.Substring(str.LastIndexOf("/") + 1);
                folder = Utilities.GetFolder(portalSettings, Definition.XSLFolderName);
                Utilities.SaveScript(portalSettings.PortalId, fileContent, fileName, folder, false);

                if (nullInteger != Null.NullInteger)
                  controller2.UpdateTabModuleSetting(nullInteger, settingName, string.Format("{0}/{1}", Definition.XSLFolderName, fileName));
                
                else if (!IsInstance)
                  controller2.UpdateModuleSetting(ModuleID, settingName, string.Format("{0}/{1}", Definition.XSLFolderName, fileName));
                
              }
            }

          }

        }
      }
      finally
      {
        System.Web.HttpContext.Current.Server.ScriptTimeout = scriptTimeout;
      }
    }





    private static string LoadScript(string HomeFilePath, int PortalId)
    {
      string str;
      FileController controller = new FileController();
      int fileId = controller.ConvertFilePathToFileId(HomeFilePath, PortalId);
      using (Stream stream = FileSystemUtils.GetFileStream(controller.GetFileById(fileId, PortalId)))
      {
        using (StreamReader reader = new StreamReader(stream))
        {
          str = reader.ReadToEnd();
        }
      }
      controller = null;
      return str;
    }





    //public bool DotNetNuke.Modules.UserDefinedTable.Serialization.IPortable2.ManagesTabModuleSettings
    //{
    //    get
    //    {
    //        return true;
    //    }
    //}





    public bool ManagesModuleSettings
    { get { return true; } }




    public bool ManagesTabModuleSettings
    { get { return true; } }



  }

}

